package com.ivy.irublesson.GetConnection;
import android.util.Log;

import com.ivy.irublesson.entity.Teacher;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/1/10.
 */

public class TeacherConn {

    private static String getTeacherData() {
        String path = "http://1.85.55.152/ZNPK/Private/List_JS.aspx?xnxq=20170&js=";
        String cookie = "ASP.NET_SessionId=5nwpkxjdtt0omjjoly0nsjeb";
        String referer = "http://1.85.55.152/ZNPK/TeacherKBFB.aspx";
        String params = " ";

        //试着解析 result 里面的字符串
        String temp = null;
        try {
            URL url = new URL(path);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setRequestMethod("GET");
            con.setRequestProperty("Cookie", cookie);
            con.setRequestProperty("Referer", referer);
            OutputStream out = con.getOutputStream();
            out.write(params.getBytes());
            out.flush();

            InputStream in = con.getInputStream();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                stream.write(buffer, 0, len);
            }
            in.close();
            stream.close();
            byte[] result = stream.toByteArray();
            temp = new String(result,"GBK");

            in.close();
            out.close();
            con.disconnect();
            return temp;
        } catch (Exception e) {

            e.printStackTrace();
            return null;
        }
    }

    public static List getTeacher(){
        String temp = getTeacherData();
        List<Teacher> teachers = new ArrayList<>();
        //截取Script代码 <select>
        String result = temp.substring(temp.indexOf("<option"), temp.lastIndexOf("</select>"));

        Document doc= Jsoup.parse(result);
        Elements nodes= doc.select("option");

        for(Element n:nodes) {
            if(n.attr("value") == "") {
                continue;
            }
            String tid = n.attr("value");
            String tname = n.text().trim();
            Teacher teacher = new Teacher( tname, tid);
			teachers.add(teacher);
        }

        return teachers;
    }
}
